/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.list;

import cn.easyplatform.contexts.ListContext;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dao.DaoException;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.ListDeleteRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.datalist.ListSelectetRowsVo;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class DeleteCmd extends AbstractCommand<ListDeleteRequestMessage> {

	/**
	 * @param req
	 */
	public DeleteCmd(ListDeleteRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		ListSelectetRowsVo srv = req.getBody();
		WorkflowContext ctx = cc.getWorkflowContext();
		ListContext lc = ctx.getList(srv.getId());
		if (lc == null)
			return MessageUtils.dataListNotFound(srv.getId());
		if (lc.getType().equals(Constants.DETAIL)) {
			for (Object[] keys : srv.getKeyList()) {
				RecordContext rc = lc.getRecord(keys);
				if (rc.getParameterAsChar("814") == 'C') {
					lc.removeRecord(rc);
					clear(cc, true, keys, lc, ctx);
				} else {
					rc.setParameter("815", true);
					rc.setParameter("814", "D");
					clear(cc, false, keys, lc, ctx);
				}
			}
		} else {
			Iterator<Object[]> itr = srv.getKeyList().iterator();
			while (itr.hasNext()) {
				Object[] keys = itr.next();
				RecordContext rc = lc.getRecord(keys);
				if (rc != null && rc.getParameterAsChar("814") == 'C') {
					//如果是新增的记录直接删除
					lc.removeRecord(keys);
					itr.remove();
				}
			}
			if (srv.getKeyList().isEmpty())
				return new SimpleResponseMessage();
			TableBean tb = cc.getEntity(lc.getBean().getTable());
			if (tb == null)
				return MessageUtils.entityNotFound(EntityType.TABLE.getName(),
						lc.getBean().getTable());
			try {
				cc.beginTx();
				BizDao dao = cc.getBizDao(tb.getSubType());
				StringBuilder sb = new StringBuilder();
				List<FieldDo> params = new ArrayList<FieldDo>();
				for (Object[] keys : srv.getKeyList()) {
					sb.setLength(0);
					params.clear();
					sb.append("delete from ").append(tb.getId())
							.append(" where ");
					params.addAll(RuntimeUtils.createPrimaryKey(tb, keys, sb));
					dao.update(cc.getUser(), sb.toString(), params, false);
				}
				params = null;
				sb = null;
				dao = null;
				cc.commitTx();
				for (Object[] keys : srv.getKeyList())
					lc.removeRecord(keys);
			} catch (DaoException ex) {
				cc.rollbackTx();
				throw ex;
			} finally {
				cc.closeTx();
			}
		}
		return new SimpleResponseMessage();
	}

	private void clear(CommandContext cc, boolean isCreate, Object[] fromKey,
			ListContext lc, WorkflowContext ctx) {
		for (String t : lc.getChildren()) {
			ListContext c = ctx.getList(t);
			c.setHostKey(fromKey);
			if (isCreate)
				c.clear(1);
			else {
				Iterator<RecordContext> itr = c.getRecords().iterator();
				while (itr.hasNext()) {
					RecordContext rc = itr.next();
					if (rc.getParameterAsChar("814") == 'C') {
						itr.remove();
						clear(cc, true, rc.getKeyValues(), c, ctx);
					} else {
						lc.lock(cc, rc.getKeyValues());
						rc.setParameter("815", true);
						rc.setParameter("814", "D");
						clear(cc, false, rc.getKeyValues(), c, ctx);
					}
				}
			}
		}
	}

	@Override
	public String getName() {
		return "list.Delete";
	}
}
